package net.zjitc.androidclassokhttp;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;


import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    Button btn_download;
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        btn_download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getRequest();
            }
        });
    }

    private void init() {
        btn_download = findViewById(R.id.btn_download);
        imageView = findViewById(R.id.imageview);
    }

    private void getRequest() {
        //1.创建request对象 设置url地址 设置请求方法
//        Request request=new Request.Builder().url("http://img.netbian.com/file/2019/0925/8aef83dfb5b87eced98c4e39af35fa96.jpg").method("GET",null).build();
        Request.Builder requestBuilder = new Request.Builder().url("http://img.netbian.com/file/2019/0925/8aef83dfb5b87eced98c4e39af35fa96.jpg");
        requestBuilder.method("GET", null);
        Request request = requestBuilder.build();
        //2.创建okHttpCilent对象
        final OkHttpClient mOkHttpClient = new OkHttpClient();
        //3.创建Call对象 参数就是Request请求对象
        Call mCall = mOkHttpClient.newCall(request);
        //4.请求加入队列 ，重写回调方法
        mCall.enqueue(new Callback() {
            //请求失败执行的方法
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            //请求成功执行的方法
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                //我写的例子是请求一张图片
                //response的body是图片bytes字节
                final byte[] bytes = response.body().bytes();
                //把butes字节组装成图片
                final Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //网络图片申请成功，更新到主线程imageView
                        imageView.setImageBitmap(bmp);

                    }
                });

            }
        });
    }
}
